const { getCurrentDateTime } = require("../modal/time.config");
const STATE = {
  LOW: 0,
  UP: 1,
};

const resolveDataFun = (arr) => {
  arr = arr.map((v) => {
    if (v.list) v.list = JSON.parse(v.list);
    if (v.scope) v.scope = JSON.parse(v.scope);

    return v;
  });
  return arr;
};

const resolveRecordDataFun = (req, list) => {
  return new Promise((resolve, reject) => {
    const p = list.map(async (item, index) => {
      if (item.record_options)
        item.record_options = JSON.parse(item.record_options);
      const res = await req.services.QuestionnaireService.findById(item.questionnaireId);
      console.log('========',res)
      item.questionnaireInfo =resolveDataFun([res])[0]
      item.userInfo = await req.services.UserService.findById(item.userId);
      item.username = item.userInfo.username;
      return item;
    });
    Promise.all(p).then((res) => {
      resolve(res);
    });
  });
};

exports.create = async (req, res) => {
  const body = req.body;
  const { title, list, introduce, scope, score, state = STATE.UP } = body;
  const data = {
    title,
    list: JSON.stringify(list),
    scope: JSON.stringify(scope),
    introduce,
    score,
    create_time: getCurrentDateTime(),
    update_time: getCurrentDateTime(),
    state,
  };
  const newData = await req.services.QuestionnaireService.create(data);
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.list = async (req, res) => {
  const body = req.body;
  const {
    title = "",
    introduce = "",
    state = "",
    page = null,
    pageSize = null,
  } = body;
  let newData = await req.services.QuestionnaireService.getList({
    where: { state },
    like: { title, introduce },
    page,
    pageSize,
  });

  let count = await req.services.QuestionnaireService.getCount({
    like: { title, introduce },
  });
  const result = resolveDataFun(newData);
  res.status(200).json({
    data: {
      list: result,
      total: count,
    },
    msg: "success",
    code: 200,
  });
};

exports.update = async (req, res) => {
  const body = req.body;
  const { title, list, introduce, id, scope, score, state } = body;
  const update_time = getCurrentDateTime();
  const data = {
    title,
    list: JSON.stringify(list),
    scope: JSON.stringify(scope),
    score,
    introduce,
    update_time,
    state,
  };
  const newData = await req.services.QuestionnaireService.update(data, {
    id,
  });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.getDetail = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.QuestionnaireService.findById(id);
  if (newData) {
    const result = resolveDataFun([newData]);
    res.status(200).json({ data: result[0], msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};

exports.del = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.QuestionnaireService.delete(Number(id));
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "删除成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};

exports.creatRecord = async (req, res) => {
  const body = req.body;
  const { result, recordOptions, questionnaireId } = body;
  const user = await req.services.UserService.decodeToken();
  const data = {
    record_options: JSON.stringify(recordOptions),
    result,
    questionnaireId,
    userId: user.userId,
    create_time: getCurrentDateTime(),
    update_time: getCurrentDateTime(),
  };
  const newData = await req.services.QuestionnaireService.createRecord(data);
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "新增成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.recordList = async (req, res) => {
  const body = req.body;
  const { page = null, pageSize = null, questionnaireId = "" } = body;
  const where = {
    questionnaireId,
  };
  const user = await req.services.UserService.decodeToken();
  if (user.role === "user") where.userId = user.id;
  let newData = await req.services.QuestionnaireService.getRecordList({
    where,
    page,
    pageSize,
  });

  let count = await req.services.QuestionnaireService.getRecordCount({
    where
  });
  const result = await resolveRecordDataFun(req, newData);
  res.status(200).json({
    data: {
      list: result,
      total: count,
    },
    msg: "success",
    code: 200,
  });
};

exports.updateRecord = async (req, res) => {
  const body = req.body;
  const { id, result, recordOptions } = body;
  const update_time = getCurrentDateTime();
  const data = {
    result,
    record_options: JSON.stringify(recordOptions),
    update_time,
  };
  const newData = await req.services.QuestionnaireService.updateRecord(data, {
    id,
  });
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "更新成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "系统错误，请重试", msg: "fail", code: 500 });
  }
};

exports.getRecordDetail = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.QuestionnaireService.findRecordById(id);
  const result = await resolveRecordDataFun(req, [newData]);
  if (newData) {
    res.status(200).json({ data: result[0], msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};

exports.delRecord = async (req, res) => {
  const body = req.query;
  const { id } = body;
  const newData = await req.services.QuestionnaireService.deleteRecord(
    Number(id)
  );
  if (newData.affectedRows === 1) {
    res.status(200).json({ data: "删除成功", msg: "success", code: 200 });
  } else {
    res.status(200).json({ data: "查无数据", msg: "fail", code: 400 });
  }
};
